<template>
  <div class="select-person-list">
    <!-- 搜索頭部 -->
    <div class="search-header">
      <input type="text" class="search-input" placeholder="搜索" v-model="searchKey" @input="searchRequest">
      <i class="search-clear" v-if="searchKey" @click="clearSearch"></i>
    </div>
    <div class="breadcrumb-nav vux-1px-b">
      <ul>
        <li v-for="(item, index) in breadcrumbData" :key="index" @click="breadcrumbClick(item, index)">
          {{item.name}}
        </li>
      </ul>
    </div>
    <div class="scroll-box" id="lazy-load-scroll" ref="scrollBox">
      <!-- 列表 -->
      <group class="list">
        <!-- 部門 -->
        <cell v-for="(item) in depList" :key="item.id" @click.native="depClick(item)"
        :title="item.name" :is-link="true" :value="item.deparmentNum">
          <img :src="depIcon" width="30" slot="icon">
        </cell>
        <!-- 員工 -->
        <cell v-for="(item, index) in empList" :key="item.userid" :title="item.name"
        @click.native="empClick(item, index)" class="emp-list">
          <x-img :src="item.avatar" :default-src="require('../../assets/images/no-header.png')"
           :offset="50" container="#lazy-load-scroll" width="30" slot="icon"></x-img>
          <span v-if="item.checked" class="icon-checked"></span>
        </cell>
        <div class="no-data" v-show="noDataShow">
          暂无数据
        </div>
      </group>
    </div>
    <!-- 報錯消息 -->
    <toast v-model="errMsgShow" type="text">{{errMsg}}</toast>
    <!-- 底部 -->
    <div class="select-bottom vux-1px-t">
      <flexbox class="title">
        <flexbox-item :gutter="0" :span="12">
          已选择{{resultList.length}}名成员
        </flexbox-item>
      </flexbox>
      <flexbox :gutter="0">
        <flexbox-item :span="8" class="select-list-box">
          <div class="select-list" :style="{ width: selectListWidth }">
            <span v-for="(item, index) in resultList" :key="index">
              {{item.name}}
            </span>
          </div>
        </flexbox-item>
        <flexbox-item :span="4">
          <button type="button" class="confirm-btn" @click="selectComplete">确认</button>
        </flexbox-item>
      </flexbox>
    </div>
    <toast v-model="toastShow" :text="toastText" type="text" class="toast-normal" :time="3000"></toast>
    <!-- 加载中 -->
    <loading class="loading-mask" :show="loadingShow" text="加载中..."></loading>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="requiredShow"
       class="turndown-confirm" title="提示" confirm-text="確認" :show-cancel-button="false">
        <p>该抄送人无法取消选中</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  import { Search, Group, Cell, Toast, Flexbox, FlexboxItem, Loading, XImg, Confirm, TransferDom } from 'vux';
  import qs from 'qs';
  import { empListAddCheckedStatus } from './index.js';
  export default {
    name: 'SelectPerson',
    data () {
      return {
        toastShow: false,       // 是否顯示提示框
        toastText: '',          // 提示框文字
        loadingShow: false,
        value: '',
        depList: [],
        empList: [],
        selectListWidth: '9999px',
        errMsg: '',
        errMsgShow: false,
        depIcon: require('../../assets/images/dep-icon.png'),
        resultList: [],
        breadcrumbData: [],
        timer: '',
        searchKey: '',
        isSearching: false,
        noDataShow: false,
        searchResponseTime: 0,
        requiredShow: false
      };
    },
    components: {
      Loading,
      Search,
      Group,
      Cell,
      Toast,
      Flexbox,
      FlexboxItem,
      XImg,
      Confirm
    },
    directives: {
      TransferDom
    },
    mounted () {
      this.firstGetResult();
    },
    methods: {
      // 初始化獲取數據
      firstGetResult: function () {
        let defaultData = {
          Id: '1',
          name: '首页',
          DepartmentId: ''
        };
        this.resultList = this.$route.params.resultList.concat();  // 這裡需要深拷貝
        this.breadcrumbData = [defaultData];
        this.depLoad(defaultData);
        setTimeout(this.selectWidth, 1000, this);
      },
      // 清除搜索框 重新加載部門
      clearSearch: function () {
        this.searchKey = '';
        this.depLoad(this.getNowPosition());
      },
      // 搜索員工
      searchRequest: function () {
        setTimeout(() => {
          this.$refs.scrollBox.scrollTop = 0;
          let depItemId = parseInt(this.getNowPosition().Id);
          let postData = {
            data: {
              Content: this.searchKey,
              DepartmentId: depItemId === 1 && this.searchKey !== '' ? 0 : depItemId
            }
          };
          this.axios.post('/Wechat/QueryDeparmentOrPerson', qs.stringify(postData))
          .then((res) => {
            let createdTime = new Date(res.data.CreatedTime).getTime();
            if (createdTime > this.searchResponseTime) {
              this.searchResponseTime = createdTime;
            } else {
              return false;
            }
            let resData = res.data.data;
            let newEmpList = resData.Users;
            if (this.searchKey === '') {
              this.depList = resData.Departments;
            } else {
              this.depList = [];
            }
            if (resData.Users === null) {
            } else if (resData.Users.length === 0) {
              this.noDataShow = true;
              this.empList = [];
              return false;
            } else {
              this.noDataShow = false;
            }
            this.resultList.forEach((item) => {
              newEmpList = empListAddCheckedStatus(newEmpList, item);
            });
            this.empList = newEmpList;
            this.noDataShow = false;
          })
          .catch((err) => {
            console.log(err);
          });
        }, 0);
      },
      // 選擇部門
      depClick: function (depItem) {
        this.depLoad(depItem);
        this.breadcrumbData.push(depItem);
      },
      // 選擇員工
      empClick: function (empItem, index) {
        this.selectListWidth = '9999px';
        if (!empItem.checked) {
          this.$set(this.empList[index], 'checked', true);
          this.resultList.push(empItem);
        } else if (empItem.removeSwitch === false) {
          this.requiredShow = true;
        } else {
          this.$set(this.empList[index], 'checked', false);
          this.resultList.forEach((item, i) => {
            if (item.userid === empItem.userid) {
              this.resultList.splice(i, 1);
            }
          });
        }
        setTimeout(this.selectWidth, 200, this);
      },
      // 計算底部寬度
      selectWidth: (_this) => {
        let selectListItemEl = document.querySelectorAll('.select-bottom .select-list span');
        let lastoneEl = selectListItemEl[selectListItemEl.length - 1];
        _this.selectListWidth = lastoneEl.offsetWidth + lastoneEl.offsetLeft + 20 + 'px';
      },
      // 報錯信息
      errorMsg: function (err) {
        clearTimeout(this.timer);
        this.errMsg = `加载失败：${err}`;
        this.errMsgShow = true;
        this.timer = setTimeout(() => {
          this.errMsg = ``;
          this.errMsgShow = false;
        }, 3000);
      },
      // 根據部門ID 加載數據
      depLoad: function (depItem) {
        this.depList = [];
        this.empList = [];
        this.loadingShow = true;
        this.axios.post('/Wechat/QueryDeparmentOrPerson', qs.stringify({
          data: {
            DepartmentId: depItem.Id
          }
        }))
        .then((res) => {
          let resData = res.data.data;
          this.loadingShow = false;
          if ((resData.Users === null || resData.Users.length === 0) && resData.Departments.length === 0) {
            this.noDataShow = true;
          } else {
            this.noDataShow = false;
          }
          if (res.data.IsSuccess) {
            // this.empList = res.data.data.users;
            let empListStr = resData.Users;
            // let newEmpListStr = [];
            this.depList = resData.Departments;
            this.resultList.forEach((item) => {
              empListStr = empListAddCheckedStatus(empListStr, item);
            });
            this.empList = empListStr;
          } else {
            this.loadingShow = false;
            this.toastShow = true;
            this.toastText = `加载失败，错误消息：${res.data.ExMessage}`;
          }
        })
        .catch((err) => {
          this.loadingShow = false;
          this.toastShow = true;
          this.toastText = `加载失败，错误消息：${err}`;
        });
      },
      // 麵包屑導航點擊事件
      breadcrumbClick: function (depItem, index) {
        if (index === this.breadcrumbData.length - 1) {
          return false;
        }
        this.searchKey = '';
        this.depLoad(depItem);
        let newBreadcrumbData = [];
        for (let i = 0; i < this.breadcrumbData.length; i++) {
          newBreadcrumbData.push(this.breadcrumbData[i]);
          if (this.breadcrumbData[i].Id === depItem.Id) {
            break;
          }
        }
        this.breadcrumbData = newBreadcrumbData;
      },
      // 獲取當前是哪一級導航
      getNowPosition: function () {
        let lastIndex = this.breadcrumbData.length - 1;
        let positionItem = this.breadcrumbData[lastIndex];
        return positionItem;
      },
      // 確定按鈕點擊事件
      selectComplete: function () {
        let toRouterName = localStorage.getItem('MakeCopyType');
        if (toRouterName) {
          let oldQueryApplyInfo;
          let newQuery;
          if (this.$route.query.applyInfo) {
            oldQueryApplyInfo = this.$route.query.applyInfo;
            newQuery = this.$route.query;
            newQuery.applyInfo = JSON.parse(oldQueryApplyInfo);
            newQuery.applyInfo.Copiers = this.resultList;
            newQuery.applyInfo = JSON.stringify(newQuery.applyInfo);
          }
          this.$router.push({
            name: toRouterName,
            params: {resultList: this.resultList},
            query: newQuery
          });
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .select-person-list{
    .scroll-box{
      padding-top: getRem(168);
    }
    .no-data{
      height: 65vh;
      line-height: 65vh;
      text-align:center;
      font-size: getRem(28);
      color: #666;
    }
    .list{
      padding-bottom: getRem(400);
      .emp-list{
        .icon-checked{
          position: absolute;
          top: getRem(24);
          right: getRem(30);
          display: inline-block;
          width: getRem(40);
          height: getRem(40);
          background: url(../../assets/images/emp-checked.png) no-repeat;
          background-size: getRem(40) getRem(40);
        }
      }
    }
    .search-header{
      position: absolute;
      top: 44px;
      width: calc(100% - #{getRem(60)});
      padding: getRem(15) getRem(30);
      background: #efeff4;
      z-index: 2;
      .search-input{
        display: block;
        border: 0;
        border-radius: 3px;
        width: calc(100% - #{getRem(40)});
        line-height: getRem(60);
        padding: 0 getRem(20);
        font-size: getRem(28);
      }
      .search-clear{
        display: block;
        width: getRem(64);
        height: getRem(64);
        position: absolute;
        top: 50%;
        right: getRem(30);
        margin-top: -#{getRem(32)};
        z-index: 1;
        background: url(../../assets/images/search-clear.png) no-repeat center center;
        background-size: getRem(32) getRem(32);
      }
    }
    .select-bottom{
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 0 0 getRem(10);
      background: #fff;
      .title{
        padding: 0 getRem(15);
        font-size: getRem(28);
        background: #f3f3f3;
        margin-bottom: getRem(10);
        line-height: getRem(60);
      }
      .select-list-box{
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
      }
      .select-list{
        height: getRem(64);
        overflow-y: auto;
        span{
          display: inline-block;
          padding: getRem(5) getRem(10);
          font-size: getRem(24);
          background: #efeff4;
          margin-left: getRem(15);
          position: relative;
          top: -#{getRem(6)};
        }
      }
      .confirm-btn{
        display: block;
        border: 0;
        color: #fff;
        width: calc(100% - #{getRem(40)});
        line-height: getRem(60);
        border-radius: getRem(5);
        font-size: getRem(28);
        margin: 0 getRem(20);
        background-image: linear-gradient(194deg,
          #fa5864 0%,
          #fc476d 100%),
        linear-gradient(
          #d91616,
          #d91616);
        background-blend-mode: normal,
          normal;
      }
    }
    .breadcrumb-nav{
      position: absolute;
      width: 100%;
      top: calc(44px + #{getRem(90)});
      z-index: 2;
      background: #fff;
      padding: 0 getRem(30);
      li{
        list-style: none;
        font-size: getRem(28);
        color: #2d8cf0;
        float: left;
        z-index: 2;
        line-height: getRem(80);
        &:last-child{
          color: #333;
        }
        &+li{
          position: relative;
          padding-left: getRem(45);
          &:before{
            content: "";
            display: block;
            width: getRem(32);
            height: getRem(32);
            background: url(../../assets/images/right-arrow.png) no-repeat;
            background-size: getRem(32) getRem(32);
            position: absolute;
            top: 50%;
            left: getRem(5);
            margin-top: -#{getRem(16)};
          }
        }
      }
    }
  }
</style>
